<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">订单编号：</label>
                  <div class="layui-input-inline mr0">
                    <input id="orderCode" name="orderCode" class="layui-input" type="text" placeholder="输入订单编号" />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">物料编号：</label>
                  <div class="layui-input-inline mr0">
                    <input id="skuCode" name="skuCode" class="layui-input" type="text" placeholder="请输入物料编号" />
                  </div>
                </div>
           
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">起止时间：</label>
                  <div class="layui-input-inline">
                    <input id="pTime" class="layui-input date-icon" type="text" placeholder="请选择创建时间" autocomplete="off" readonly />
                    <input name="startTime" id="sTime" style="display: none" />
                    <input name="endTime" id="eTime" style="display: none" />
                  </div>
                </div>
                <div class="layui-inline">  
                  <label class="layui-form-label w-auto">物料名称：</label>
                  <div class="layui-input-inline mr0">
                    <input id="skuName" name="skuName" class="layui-input" type="text" placeholder="请输入物料名称" />
                  </div>
                </div>
              </div>
              <div class="query-rt">
                <div class="layui-inline">
                  <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                  <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                  <button id="orderDetailBtnExport" class="layui-btn icon-btn color-green">导出</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <table class="layui-table" id="selOrderDateilTable" lay-filter="selOrderDateilTable"></table>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="selOrderDateail-table-bar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- js部分 -->
<script>
  layui.use(["layer", "form", "table", "admin", "laytpl", "laydate", "util"], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var laydate = layui.laydate;
    //时间范围
    laydate.render({
      elem: "#pTime",
      type: "date",
      range: true,
      done: function (value, date, endDate) {
        if (value) {
          var dateValue = value.split(" - ");
          $("input[name='startTime']").val(dateValue[0] + " 00:00:00");
          $("input[name='endTime']").val(dateValue[1] + " 23:59:59");
        } else {
          $("input[name='startTime']").val("");
          $("input[name='endTime']").val("");
        }
      }
    });
    // 渲染表格
    var insTb = table.render({
      elem: "#selOrderDateilTable",
      url: config.base + "enterprise/sell/admin/orderProDetail/list",
      where: {
        access_token: config.getToken().access_token
      },
      page: true,
      cellMinWidth: 100,
      cols: [
        [
          { type: "numbers" },
          { field: "orderCode", align: "center", title: "订单编号", width: 150 },
          { field: "customerName", align: "center", title: "客户名称", width: 120 },
          {
            field: "skuCode",
            align: "center",
            title: "物料编号",
            width: 120,
            templet: function (d) {
              return d.skuCode ? d.skuCode : "未关联内部料号";
            }
          },
          {
            field: "skuName",
            align: "center",
            title: "物料名称",
            width: 120,
            templet: function (d) {
              return d.skuName ? d.skuName : "未关联内部料号";
            }
          },
          {
            field: "skuSpec",
            align: "center",
            title: "规格型号",
            width: 120,
            templet: function (d) {
              return d.skuSpec ? d.skuSpec : "未关联内部料号";
            }
          },
          { field: "cusSkuCode", align: "center", title: "客户物料编号", width: 120 },
          { field: "cusSkuName", align: "center", title: "客户物料名称", width: 120 },
          { field: "cusSkuSpec", align: "center", title: "客户规格型号", width: 120 },
          { field: "selQuality", align: "center", title: "数量" },
          { field: "price", align: "center", title: "单价" },
          {
            field: "totalPrice",
            align: "center",
            title: "总价"
          },
          { field: "createTime", align: "center", title: "创建时间" },
          { field: "creatorName", align: "center", title: "创建人" }
        ]
      ]
    });

    // 工具条点击事件
    table.on("tool(selOrderDateail-table)", function (obj) {});

    //监听排序
    table.on("sort(selOrderDateilTable)", function (obj) {
      table.reload("selOrderDateilTable", {
        initSort: obj,
        where: {
          sort: obj.field,
          order: obj.type
        }
      });
    });

    $("#orderDetailBtnExport").click(function () {
      let skuCode = $("#skuCode").val();
      let skuName = $("#skuName").val();
      let orderCode = $("#orderCode").val();
      // 创建一个对象来保存所有可能的查询参数
      let queryParams = {
        skuCode: skuCode,
        skuName: skuName,
        orderCode: orderCode
      };

      // 过滤掉值为 undefined 的属性
      queryParams = Object.keys(queryParams)
        .filter((key) => queryParams[key] !== undefined && queryParams[key] !== "")
        .reduce((obj, key) => {
          obj[key] = queryParams[key];
          return obj;
        }, {});

      // 将过滤后的参数对象转换为查询字符串
      let queryString = new URLSearchParams(queryParams).toString();

      // 获取当前日期和时间
      let now = new Date();
      let year = now.getFullYear();
      let month = String(now.getMonth() + 1).padStart(2, "0"); // 注意：getMonth() 返回值是 0-11
      let day = String(now.getDate()).padStart(2, "0");
      let hour = String(now.getHours()).padStart(2, "0");
      let minute = String(now.getMinutes()).padStart(2, "0");
      let second = String(now.getSeconds()).padStart(2, "0");

      // 格式化日期和时间为 YYYYMMDD_HHMMSS 形式
      let formattedDateTime = `${year}${month}${day}_${hour}${minute}${second}`;

      // 设置下载文件名为 "产品数据_YYYYMMDD_HHMMSS.xls"
      let fileName = `正式订单明细表_${formattedDateTime}.xls`;

      // 创建完整的URL，包括查询参数和文件名作为额外参数（如果后端支持的话）
      let fullUrl = config.base + "enterprise/sell/admin/orderProDetail/export?" + queryString + "&fileName=" + encodeURIComponent(fileName);

      // 使用 window.open 打开新页面进行下载
      window.open(fullUrl);
      // 注意：这里假设后端能够处理 fileName 参数，并根据它设置响应头中的 Content-Disposition 来指定下载文件名。
      // 如果后端不支持通过 URL 参数指定文件名，你可能需要调整后端代码来接受这种请求方式。
    });

    // 搜索
    form.on("submit(formSubSearchLog)", function (data) {
      insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
    });

    // 重置搜索
    form.on("submit(resets)", function (data) {
      $(".lay-header").find("select").val("");
      $(".lay-header").find("input").val("");
      let field = data.field;
      for (let key in field) {
        field[key] = "";
      }
      insTb.reload({ where: field, page: { curr: 1 } }, "data");
    });

    // 导出excel
    $("#finishedOrderDetailBtnExport").click(function () {
      var checkRows = table.checkStatus("selOrderDateilTable");
      if (checkRows.data.length == 0) {
        layer.msg("请选择要导出的数据", { icon: 2 });
      } else {
        table.exportFile(insTb.config.id, checkRows.data, "xls");
      }
    });
  });
</script>
